package com.yls.except.util;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.springframework.web.multipart.MultipartFile;

public class Upload {
	public static void upload (MultipartFile file, String getImagePath, String fileNewName) throws IOException {
		int w = 0;
		int h = 0;
		File image = new File(getImagePath);
		if (!image.exists() && !image.isDirectory()) {
			image.mkdirs();
		}
		BufferedImage srcBufferImage = ImageIO.read(file.getInputStream());
		ScaleImage scaleImage = ScaleImage.getInstance();
		int weight = srcBufferImage.getWidth();
		int height = srcBufferImage.getHeight();
		System.out.println(weight + ":" + height);
		if(weight > 1000 && weight >= height) {
			w = 1000;
			h = (int)(((1 - (weight - 1000d) / weight)) * height + 0.5); 
		} else if(height > 1000 && height > weight) {
			h = 1000;
			w = (int)(((1 - (height - 1000d) / height)) * weight + 0.5);
		} else {
			w = weight;
			h = height;
		}
		System.out.println(weight + ":" + height);
		BufferedImage scaledImage = scaleImage.imageZoomOut(srcBufferImage, w, h);
		FileOutputStream out = new FileOutputStream(getImagePath + "/"
				+ fileNewName);
		ImageIO.write(scaledImage, "jpeg", out); 
		/*FileUtils.copyInputStreamToFile(file.getInputStream(), new File(
				getImagePath, fileNewName));*/
	}
}
